<template>
  <div 
    class="report"
    element-loading-text="数据加载中"
    element-loading-spinner="el-icon-loading"
    v-loading="loading"
  >
    <div class="form">
      <div class="left">
        <div class="title">
          {{ buName }}{{ isCreate ? writeablePeriod : dcPeriod }}季度数字化覆盖度{{
            tabKey === 'coverStatus' ? '现状' : '目标'
          }}{{ isCreate || fgState === '待提交' ? '-填报' : '' }}
        </div>
        <Tooltip placement="right-start" max-width="500" v-if="isCreate || fgState">
          <Icon type="ios-help-circle-outline" size="25" />
          <template #content>
            <div>
              <p class="tip_content">1.规划中/建设中则填0</p>
              <p class="tip_content">2.不涉及则填'-'</p>
              <p class="tip_content">3.已上线则填写已上线的数量</p>
            </div>
          </template>
        </Tooltip>
      </div>
      <div class="right">
        <slot name="btnGroup"></slot>
        <div class="upload" v-if="(tabKey === 'coverStatus'&& fgState === '待提交') || isCreate">
          <Upload
            ref="upload"
            :max-size="15 * 1024"
            :on-exceeded-size="handleMaxSize"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :data="uploadData"
            :on-success="handleSuccess"
            :on-error="handleError"
            :on-remove="handlerRemove"
            :show-upload-list="true"
            :default-file-list="fileConfig.attachment || []"
            :on-preview="downLoad"
            :before-upload="handleBeforeUpload"
          >
            <RPButton text="上传附件" ref="search" />
          </Upload>
        </div>
        <!-- <RPButton class="btn" v-if="tabKey === 'coverGoal'" text="深度及广度权重配置" @click="weightHandle()" /> -->
        <RPButton v-if="tabKey === 'coverGoal'" text="组织管理" @click="orgHandle()" />
        <RPButton v-if="tabKey === 'coverGoal'" text="关键业务环节配置" @click="keyHandle()" />
        <RPButton v-if="tabKey === 'coverStatus'" text="测算覆盖度" @click="currentCompute()" :disabled="inCompute" />
        <!-- <RPButton class="btn" text="暂存" @click="tempHandle()" /> -->
        <RPButton text="提交" @click="submit()" />
        <RPButton btnType="reset" text="取消" ref="search" @click="cancel" />
      </div>
    </div>
    <cover-table
      :columns="columns"
      :data="tableData"
      :total="total"
      :id="id"
      :height="height"
      :fgState="fgState"
      :tabKey="tabKey"
      @changePage="changePage"
    >
    </cover-table>
  </div>
</template>

<script>
// import FileModal from './components/FileModal.vue'
import CoverTable from './components/Table.vue'
import PreCompute from './components/PreCompute.vue'
import weightEdit from './goal/weightEdit.vue'
import orgManage from './goal/orgManage/orgManege.vue'
import cover2Api from '@/api/cover2'
import coverApi from '@/api/cover'
import treeApi from '@/api/treeApi'
export default {
  name: 'createStatus',
  components: {
    CoverTable
  },
  props: {
    height: {
      type: Number,
      default: 255
    },
    tabKey: {
      type: String,
      default: 'coverStatus'
    },
    isCreate: {
      type: Boolean,
      default: false
    },
    buCode: {
      type: String,
      default: ''
    },
    dcPeriod: {
      type: String,
      default: ''
    },
    fgState: {
      type: String,
      default: ''
    }
    // buName: {
    //   type: String,
    //   default: ''
    // }
  },

  data() {
    return {
      inCompute: false,
      loading: true,
      tableData: [],
      columns: [],
      total: 0,
      id: '',
      changed: false,
      uploadHeaders: { authorization: localStorage.Authorization ? `Bearer ${localStorage.Authorization}` : '' },
      uploadData: { bizId: '0' },
      uploadUrl: coverApi.getPlantaskUploadUrl(),
      fileConfig: {
        id: '',
        attachment: []
      }
    }
  },
  computed: {
    pageSize() {
      // return this.fgState === '审核通过' ? 10 : 10
      return 1000
    },
    writeablePeriod() {
      return this.$store.state.writeablePeriod
    },
    buName() {
      return this.$store.state.userBu.value
    }
  },
  created() {
    this.init(1, this.pageSize)
  },
  methods: {
    // 查询现状单条数据
    async getStatusData(params) {
      return cover2Api.getStatusById(params).then(res => {
        this.total = res.data.data.total
        try {
          this.fileConfig.attachment = JSON.parse(res.data.data.templateConfig.attachment)
          // this.fileConfig.attachment = JSON.parse(res.data.data.attachment)
        } catch (error) {
          console.error('Error parsing JSON:', error)
        }
        return res.data
      }).catch(error => {
        console.error(error)
      }) .finally(() => {
        this.loading = false
      })
    },
    // 查询目标单条数据
    async getGoalData(params) {
      return cover2Api.getGoalById(params).then(res => {
        this.total = res.data.data.total
        return res.data
      }).finally(() => {
        this.loading = false
      })
    },
    // 获取状态新建表格
    getCreateStatus(params) {
      return cover2Api.getCreateStatusData(params).then(res => {
        this.total = res.data.data.total
        return res.data
      }).finally(() => {
        this.loading = false
      })
    },
    // 获取目标新建表格
    getCreateGoal(params) {
      return cover2Api.getCreateGoalData(params).then(res => {
        this.total = res.data.data.total
        return res.data
      }).finally(() => {
        this.loading = false
      })
    },
    changePage(currentPage, pageSize) {
      this.init(currentPage, pageSize)
    },
    getNodeTreeByTreeCode() {
      let bucode = this.$store.state.userBu.key
      return treeApi.getNodeTreeByTreeCode('GJ-' + bucode).then(res => {
        return res
      })
    },
    getTree() {
      let bucode = this.$store.state.userBu.key
      return treeApi.getNodeTreeByTreeCode('ZZ-' + bucode).then(res => {
        return res
      })
    },
    async init(currentPage = 1, pageSize = 1000) {
      let host = location.host
      if (host.includes('sit')) {
        host = 'crinfo-uat.test.crcloud.com'
      }
      // 判断是新建还是详情，状态还是目标
      let params = {
        buCode: this.buCode,
        dcPeriod: this.dcPeriod || this.$store.state.writeablePeriod,
        refPreviousData: false,
        currentPage,
        pageSize,
        buName: this.$store.state.userBu.value,
        pcUrl: encodeURIComponent(
          `https://${host}/form.html?formType=${this.tabKey}&buCode=${this.$store.state.userBu.key}&dcPeriod=${this.$store.state.writeablePeriod}&type=cover`
        )
      }
      let res = {}
      if (this.isCreate) {
        params.org = await this.getTree()
        params.sys = await this.getNodeTreeByTreeCode()
        res = this.tabKey === 'coverStatus' ? await this.getCreateStatus(params) : await this.getCreateGoal(params)
      } else {
        res = this.tabKey === 'coverStatus' ? await this.getStatusData(params) : await this.getGoalData(params)
      }
      this.fileConfig.id = res.data.templateConfig?.id
      this.fileConfig.attachment = JSON.parse(res.data.templateConfig?.attachment || '[]')
      this.id = res.data.id
      this.tableData = res.data.data
      this.columns = res.data.tableHeaderData
    },
    async getEditData() {
      let params = {
        buCode: this.buCode,
        dcPeriod: this.dcPeriod || this.$store.state.writeablePeriod,
        refPreviousData: false,
        currentPage: 1,
        pageSize: 1000
      }
      let res = this.tabKey === 'coverStatus' ? await this.getStatusData(params) : await this.getGoalData(params)
      this.id = res.data.id
      this.tableData = res.data.data
      this.columns = res.data.tableHeaderData
    },
    weightHandle() {
      new this.$pageModal(weightEdit)
    },
    orgHandle() {
      new this.$sidelipPage(
        orgManage,
        {
          props: {
            title: '组织管理',
            comp: 'orgManage',
            dcPeriod: this.dcPeriod,
            changeFunc: this.onChange
          }
        },
        data => {
          if (this.changed) {
            this.getEditData()
          }
        }
      )
    },
    keyHandle() {
      new this.$sidelipPage(
        orgManage,
        {
          props: {
            title: '关键业务环节',
            comp: 'keyBiz',
            dcPeriod: this.dcPeriod,
            changeFunc: this.onChange
          }
        },
        data => {
          if (this.changed) {
            this.getEditData()
          }
        }
      )
    },
    currentCompute() {
      new this.$pageModal(
        PreCompute,
        {
          props: {
            buCode: this.buCode, dcPeriod: this.dcPeriod 
          }
        }
      )
    },
    // quoteHandle() {
    //   let params = { buCode: this.buCode, dcPeriod: this.$store.state.writeablePeriod }
    //   if (this.tabKey === 'coverStatus') {
    //     cover2Api.getLastStatusData(params).then(res => {
    //       this.tableData = result.data.data
    //     })
    //   } else {
    //     cover2Api.getLastGoalData(params).then(res => {
    //       this.tableData = result.data.data
    //     })
    //   }

    // },
    // tempHandle() {
    //   this.shouldFetch = true
    //   this.isSave = true
    // },
    submit() {
      // 附件必传
      if (this.fileConfig.attachment.length === 0 && this.tabKey === 'coverStatus') {
        return this.$message.error({
          content: '请上传附件',
          duration: 2
        })
      }
      this.$confirm({
        title: '提交',
        content: '是否要提交?'
      }).then(() => {
        let host = location.host
        if (host.includes('sit')) {
          host = 'crinfo-uat.test.crcloud.com'
        }
        let pcUrl = encodeURIComponent(
          `https://${host}/form.html?formType=${this.tabKey}&buCode=${this.$store.state.userBu.key}&dcPeriod=${this.$store.state.writeablePeriod}&type=cover`
        )
        const params = {
          id: this.id,
          dcPeriod: this.$store.state.writeablePeriod,
          buCode: this.$store.state.userBu.key,
          buName: this.buName,
          pcUrl
        }
        if (this.tabKey === 'coverStatus') {
          cover2Api.createStatusData(params).then(res => {
            if (res.data.code === 400) {
              this.$Message.error({
                content: res.data.msg || '提交失败',
                duration: 3
              })
              return
            }
            this.$Message.success({
              content: '新建成功',
              duration: 3
            })
            this.$emit('Close', 1)
          })
        } else {
          cover2Api.createGoalData(params).then(res => {
            if (res.data.code === 400) {
              this.$Message.error({
                content: res.data.msg || '提交失败',
                duration: 3
              })
              return
            }
            this.$Message.success({
              content: '新建成功',
              duration: 3
            })
            this.$emit('Close', 1)
          })
        }
      })
    },
    cancel() {
      this.$emit('Close')
    },

    onChange() {
      this.changed = true
    },

    getLeafNodes(nodes) {
      let result = []
      for (const node of nodes) {
        if (node.children && node.children.length > 0) {
          // 如果当前节点有children，则递归调用getLeafNodes
          if (Array.isArray(node.children)) {
            result.push(...this.getLeafNodes(node.children))
          }
        } else {
          // 如果当前节点没有children，说明它是叶子节点，将其添加到结果数组中
          result.push(node)
        }
      }
      return result
    },
    handleSuccess(response, file, fileList) {
      this.fileConfig.attachment.push({ name: file.name, fileId: response.data })
      cover2Api
        .updateFile({ id: this.fileConfig.id, attachment: JSON.stringify(this.fileConfig.attachment) })
        .then(res => {
          if (res.code === 200) {
            this.$message.success('上传成功')
          }
        })
    },
    handlerRemove(file, fileList) {
      let index = this.fileConfig.attachment.findIndex(item => item.fileId === file.fileId)
      this.fileConfig.attachment.splice(index, 1)
      cover2Api
        .updateFile({ id: this.fileConfig.id, attachment: JSON.stringify(this.fileConfig.attachment) })
        .then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功')
          }
        })
    },
    handleError(data) {
      this.$Message.error({
        content: '上传失败',
        duration: 3
      })
    },
    handleMaxSize(data) {
      this.$Message.warning({
        content: '附件不能超过15M',
        duration: 3
      })
    },
    handleBeforeUpload() {
      const check = this.fileConfig.attachment.length < 1
      if (!check) {
        this.$Message.warning({
          content: '只能上传一个附件',
          duration: 3
        })
      }
      return check
    },
    downLoad(file) {
      coverApi.plantaskDownloadFile(file.fileId)
    }
  }
}
</script>

<style lang="less" scoped>
/deep/.el-input .el-input__inner {
  color: #000;
  font-size: 16px;
}
.report {
  .form {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-left: 20px;
    margin-right: 20px;
    margin-top: 5px;
    margin-bottom: 5px;
    .left {
      display: flex;
      .title {
        font-size: 18px;
        font-weight: 700;
      }
    }
    .right {
      display: flex;

      .upload {
        .ivu-upload {
          height: 30px;
          display: flex;
          flex-flow: row-reverse;
          // margin-top: -8px;
          /deep/.ivu-upload-list {
            display: flex;
            justify-content: flex-end;
            align-items: center;
            margin-top: -4px;
          }
        }
      }
      .ivu-btn {
        margin-left: 10px;
      }
    }
  }
}
</style>
